from flask import abort, jsonify
from flask_restful import Resource
from requests.exceptions import HTTPError
import requests
import os
from werkzeug.exceptions import HTTPException
import geocoder

# from app import app


class WeatherCity(Resource):
    def get(self, city):
        """
        search weather by city
        ---
        tags:
          - weather
        parameters:
          - in: path
            name: city
            required: true
            default: me
            description: The city name
            type: string
        responses:
          200:
            description: The weather of the city
            schema:
              id: Weather
              properties:
                city:
                  type: string
                  default: now city
                code:
                    type: integer
                    default: 200
                fxLink:
                    type: string
                    default: ''
                now:
                    type: object
                    properties:
                        cloud:
                            type: string
                            default: ''
                        dew:
                            type: string
                            default: ''
                        feelsLike:
                            type: string
                            default: ''
                        humidity:
                            type: string
                            default: ''
                        icon:
                            type: string
                            default: ''
                        obsTime:
                            type: string
                            default: ''
                        precip:
                            type: string
                            default: ''
                        pressure:
                            type: string
                            default: ''
                        temp:
                            type: string
                            default: ''
                        text:
                            type: string
                            default: ''
                        vis:
                            type: string
                            default: ''
                        wind360:
                            type: string
                            default: ''
                        windDir:
                            type: string
                            default: ''
                        windScale:
                            type: string
                            default: ''
                        windSpeed:
                            type: string
                            default: ''
                refer:
                    type: object
                    properties:
                        license:
                            type: array
                            items:
                                type: string
                                default: ''
                        sources:
                            type: array
                            items:
                                type: string
                                default: ''
                updateTime:
                    type: string
                    default: now time        
        """
        try:
            # 使用和风天气API
            # 查询城市id
            if city == "me":
                city = get_location()
            geo_api = f'https://geoapi.qweather.com/v2/city/lookup?location={city}&key={os.environ.get("HEWEATHER_API_KEY")}'
            geo_response = requests.get(geo_api)
            geo_response.raise_for_status()
            city_id = geo_response.json()["location"][0]["id"]
            # 查询天气
            weather_api = f'https://devapi.qweather.com/v7/weather/now?location={city_id}&key={os.environ.get("HEWEATHER_API_KEY")}'
            response = requests.get(weather_api)
            response.raise_for_status()
            data = response.json()
            data.update({"code": 200, "city": city})
            return jsonify(data)

        except HTTPError as http_err:
            abort(
                jsonify({"code": 400, "message": f"HTTP error occurred: {http_err}"}))
        except Exception as err:
            print(f"Other error occurred: {err}")
            abort(
                jsonify({"code": 404, "message": f"Other error occurred: {err}"}))


def get_location():
    """get location by ip

    Returns:
        _type_: the city name
    """
    g = geocoder.ip("me")
    return g.city
